<template>
  <div v-if="showNotification" class="call-notification-overlay">
    <div class="call-notification">
      <!-- 头像 -->
      <div class="caller-avatar">
        <div class="avatar-placeholder">{{ targetUserName }}</div>
      </div>

      <!-- 邀请信息 -->
      <div class="call-message">
        邀请你视频通话
      </div>

      <!-- 操作按钮 -->
      <div class="call-actions">
        <button @click="rejectCall" class="reject-button">
          <svg t="1755612835976" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7917" width="48" height="48"><path d="M0 512c0 282.766222 229.233778 512 512 512s512-229.233778 512-512S794.766222 0 512 0 0 229.233778 0 512z" fill="#FF2E2E" p-id="7918"></path><path d="M394.410667 477.098667s5.404444-24.519111 42.439111-29.297778c37.063111-4.721778 113.123556-4.778667 147.911111 6.001778 34.872889 10.865778 29.127111 40.988444 29.127111 40.988444s2.304 47.160889 5.774222 51.825778c3.413333 4.721778 8.732444 34.133333 82.176 39.594667 73.443556 5.518222 70.144-9.671111 69.831111-38.855112-0.227556-29.098667-8.647111-76.487111-37.12-108.145777-28.330667-31.687111-65.706667-67.640889-173.056-81.322667-107.320889-13.653333-216.149333 9.045333-255.061333 39.196444-38.968889 30.264889-65.820444 51.854222-63.345778 115.399112 2.446222 63.715556 0.341333 72.675556 37.319111 74.552888 36.835556 2.104889 94.72-12.515556 100.408889-17.152 5.688889-4.551111 14.165333-10.922667 14.307556-31.573333 0.170667-20.593778-1.024-32.540444-1.024-32.540444l0.312889-28.672z" fill="#FFFFFF" p-id="7919"></path></svg>
        </button>
        <button @click="acceptCall" class="accept-button">
          <svg t="1755671072554" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2351" width="48" height="48"><path d="M511.868892 1023.999069A512.008492 512.008492 0 0 1 312.627803 40.489527a512.000737 512.000737 0 0 1 398.482177 943.289056A508.665833 508.665833 0 0 1 511.868892 1023.999069zM314.349544 364.773981a55.149995 55.149995 0 0 0-21.45196 5.219512A37.653386 37.653386 0 0 0 271.445624 406.53783v211.192451a37.64563 37.64563 0 0 0 21.45196 36.536581 55.157751 55.157751 0 0 0 21.45196 5.219512h256.213647a55.173262 55.173262 0 0 0 21.459716-5.219512 37.64563 37.64563 0 0 0 21.444204-36.536581V407.763213a41.019312 41.019312 0 0 0-11.113759-30.246798A50.000284 50.000284 0 0 0 570.563191 364.773981zM741.434334 385.450382a7.344543 7.344543 0 0 0-5.475446 2.125032l-84.605723 65.74413a10.857825 10.857825 0 0 0-3.792483 7.600478v104.987412a9.128329 9.128329 0 0 0 3.792483 7.600477l84.582456 65.736375a9.593664 9.593664 0 0 0 6.305294 2.520566 9.306707 9.306707 0 0 0 5.025622-1.287428A8.631971 8.631971 0 0 0 752.292159 631.643808v-236.545473a9.306707 9.306707 0 0 0-6.251005-8.833616 14.572752 14.572752 0 0 0-4.653353-0.845359z" fill="#1afa29" p-id="2352"></path></svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onUnmounted, inject} from 'vue'
import type { Ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useCallStore } from '@/stores/call'
import axios from "axios";  // 导入Pinia Store

const router = useRouter()
const callStore = useCallStore()  // 获取通话状态Store

const showNotification = ref(false)  // 控制弹窗显示和隐藏
const callerName = ref('邀请方')  // 默认显示名称

const route = useRoute()
const token = ref(localStorage.getItem('token')) // 获取Token
const userId = ref('-1') // 存储解析后的用户id
const targetUserName = ref('邀请方')

const ws = inject('websocket') as Ref<WebSocket | null>

// 工具函数：从Token解析用户ID
const getUserIdFromToken = (token: string) => {
  if (!token) return '';
  try {
    const payloadBase64 = token.split('.')[1];
    const decoded = JSON.parse(atob(payloadBase64));
    return decoded.sub;
  } catch (error) {
    console.error('Token解析失败:', error);
    return '';
  }
};

// 组件挂载时监听通话邀请
onMounted(() => {
  userId.value = getUserIdFromToken(token.value);  // 解析Token获取用户ID
  console.log('用户ID：', userId.value)

  callStore.$onAction(({ name, args }) => {
    if (name === 'receiveCall') {
      const invitation = args[0] as {
        roomId: string;
        callerId: string;
        callerName?: string
      }

      showNotification.value = true
      callerName.value = invitation.callerName || invitation.callerId

      console.log('222222222')
      console.log(callerName.value)

      axios.get('http://localhost:8020/user/GetUserInfo', {
        params: {
          userId: callerName.value,
        }
      }).then(res => {
        console.log('用户数据加载成功：' + res.data);
        targetUserName.value = res.data.username;
        console.log('用户名：' + targetUserName.value)
      })
    }
  })
})

// 接听通话
const acceptCall = async () => {
  try {
    showNotification.value = false
    await router.push({
      name: 'VideoChat',
      query: {
        userId: route.query.userId,
        roomId: callStore.currentRoomId,
        role: 'receiver',
        callerId: callStore.callerName
      }
    })
  } catch (error) {
    console.error('接听失败:', error)
    showNotification.value = true
  }
}

// 拒绝通话
const rejectCall = async () => {
  try {
    // 发送拒绝通知
    if (ws?.value?.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify({
        type: 'call_ended',
        roomId: callStore.currentRoomId,
        senderId: userId.value,
        data: {
          timestamp: Date.now(),
          reason: 'user_rejected'
        }
      }));
    }

    // 更新本地状态
    callStore.callStatus = 'idle';
    showNotification.value = false;

    // 强制刷新页面
    const currentPath = router.currentRoute.value.path;
    if (currentPath !== '/') {
      // 如果不在首页，先跳转再刷新
      router.push('/').then(() => {
        window.location.reload();
      });
    } else {
      // 如果在首页直接刷新
      window.location.reload();
    }

  } catch (error) {
    console.error('拒绝处理失败:', error);
    showNotification.value = false;
  }
};

onUnmounted(() => {
  callStore.$onAction(() => {})  // 清空action监听
})
</script>

<style scoped>
.call-notification-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.call-notification {
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  padding: 2rem;
  border-radius: 12px;
  text-align: center;
  color: white;
}

.caller-avatar {
  width: 80px;
  height: 80px;
  margin: 0 auto 1rem;
  border-radius: 50%;
  background: #4a4e69;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-placeholder {
  font-size: 2rem;
}

.call-message {
  font-size: 1.2rem;
  margin-bottom: 1.5rem;
}

.call-actions {
  display: flex;
  gap: 2rem;
  justify-content: center;
}

.reject-button, .accept-button {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.reject-button {
  background: #ff5c5c;
}

.accept-button {
  background: #4ade80;
}
</style>